package com.mrd.gtimp.business.action;

import com.mrd.exception.QueryException;
import com.mrd.framework.config.web.json.annotation.JField;
import com.mrd.framework.config.web.json.annotation.Json;
import com.mrd.framework.ui.Jqgrid;
import com.mrd.framework.ui.filter.SearchRule;
import com.mrd.framework.ui.filter.SearchRuleOption;
import com.mrd.gtimp.business.entity.GoodsView;
import com.mrd.gtimp.business.service.GoodsViewBiz;
import com.mrd.gtimp.fix.ChnToCodeFix;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

import javax.annotation.Resource;

@Controller
@RequestMapping("/business")
public class GoodsViewAction {

	private static final long	serialVersionUID	= 4786063344926501638L;

	@Resource
	private GoodsViewBiz		goodsViewBiz;

	private List<GoodsView>		goodsViews;

	private GoodsView			goodsView;
	@Resource
	private ChnToCodeFix		chnToCodeFix;

	@RequestMapping("/goodsView-main")
	public String main(String goodsViewName,String type,Model model) {
		if(StringUtils.isNotEmpty(goodsViewName)) {
			model.addAttribute("goodsViewName", goodsViewName);
		}
		if(StringUtils.isNotEmpty(type)) {
			model.addAttribute("type", type);
		}
		return "/gtimp/goodsView/main";
	}

	@RequestMapping("/goodsView-findList")
	@ResponseBody
	@Json({@JField("name"), @JField("code_t"), @JField("code_s"), @JField("goods_mode"),
	        @JField("unit"), @JField("legal_unit"), @JField("second_unit"), @JField("unitCode"),
	        @JField("secondUnitCode"), @JField("legalUnitCode") })
	public Page<GoodsView> findList(String goodsViewName,Jqgrid jqgrid) {
		if(StringUtils.isNotEmpty(goodsViewName) && jqgrid.getFilters() == null) {
			jqgrid.addRule(new SearchRule("name", SearchRuleOption.cn, goodsViewName));
		}
		try {
			Page<GoodsView> goodsViewPage = goodsViewBiz.findByJqgrid(jqgrid);
			for(GoodsView view : goodsViewPage) {
				view.setLegalUnitCode(chnToCodeFix.unit(view.getLegal_unit()));
				view.setUnitCode(chnToCodeFix.unit(view.getUnit()));
				view.setSecondUnitCode(chnToCodeFix.unit(view.getSecond_unit()));
			}
			return goodsViewPage;
		} catch (QueryException e) {
			e.printStackTrace();
		}
		return null;
	}

	public List<GoodsView> getGoodsViews() {
		return goodsViews;
	}

	public void setGoodsViews(List<GoodsView> goodsViews) {
		this.goodsViews = goodsViews;
	}

	public GoodsView getGoodsView() {
		return goodsView;
	}

	public void setGoodsView(GoodsView goodsView) {
		this.goodsView = goodsView;
	}
}
